package com.jeecms.wicool.action.material;

import static com.jeecms.common.page.SimplePage.cpn;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import com.jeecms.cms.manager.main.CmsLogMng;
import com.jeecms.cms.web.CmsUtils;
import com.jeecms.cms.web.WebErrors;
import com.jeecms.common.page.Pagination;
import com.jeecms.common.web.CookieUtils;
import com.jeecms.wicool.entity.material.WeixinConfiguration;
import com.jeecms.wicool.entity.material.WeixinMaterial;
import com.jeecms.wicool.entity.material.WeixinMaterialDetail;
import com.jeecms.wicool.entity.material.WeixinMenu;
import com.jeecms.wicool.entity.product.Product;
import com.jeecms.wicool.entity.shops.ShopInfo;
import com.jeecms.wicool.entity.util.Dictionary2;
import com.jeecms.wicool.manager.material.WeixinConfigurationMng;
import com.jeecms.wicool.manager.material.WeixinMaterialDetailMng;
import com.jeecms.wicool.manager.material.WeixinMaterialMng;
import com.jeecms.wicool.manager.material.WeixinMenuMng;
import com.jeecms.wicool.manager.shops.WiShopInfoMng;
import com.jeecms.wicool.manager.util.DictionaryMng;

/**
 * 会员卡Action
 */
@Controller
public class WeixinMaterialAct {
	private static final Logger log = LoggerFactory
			.getLogger(WeixinMaterialAct.class);

	@RequestMapping("/material/v_listWeixinMaterial.do")
	public String list(Integer shopId, Short messageType, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		Pagination pagination = manager.getPage(shopId, messageType,
				cpn(pageNo), CookieUtils.getPageSize(request),CmsUtils.getUser(request));
		List<WeixinMaterial> list = (List<WeixinMaterial>) pagination.getList();
		for (WeixinMaterial c : list) {
			c.setMessageTypeName(dicMng.findByDicCode("message_type",
					c.getMessageType()).getDicName());
		}
		List<Dictionary2> listMessageType = dicMng.getList("message_type");
		List<ShopInfo> listShop = shopMng.getAll(CmsUtils.getUser(request));
		model.addAttribute("pagination", pagination);
		model.addAttribute("shopId", shopId);
		model.addAttribute("listShop", listShop);
		model.addAttribute("listMessageType", listMessageType);
		model.addAttribute("messageType", messageType);
		return "material/list_WeixinMaterial";
	}
	/**
	 * 微信配置list
	 */
	@RequestMapping("/material/v_listWeixinConfiguration.do")
	public String listWeixinConfiguration(Integer weixinMaterialId, Short configType,Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		Pagination pagination = weixinConfigurationMng.getPage(weixinMaterialId, configType,
				cpn(pageNo), CookieUtils.getPageSize(request));
		List<WeixinConfiguration> list = (List<WeixinConfiguration>) pagination.getList();
		for (WeixinConfiguration c : list) {
			if(c.getConfigType()!=null){
			c.setConfigTypeName(dicMng.findByDicCode("weixin_config_type",
					c.getConfigType()).getDicName());
			}
			if(c.getSpecialServiceCode()!=null){
			c.setSpecialServiceCodeName(dicMng.findByDicCode("special_service",
					Short.parseShort(c.getSpecialServiceCode().toString())).getDicName());
			}
			if(c.getIsMain()!=null){
				if(c.getIsMain()==1)
				c.setIsMainName("是");
			}else{
				c.setIsMainName("否");
			}
		}
		List<Dictionary2> listConfigType = dicMng.getList("weixin_config_type");
		model.addAttribute("pagination", pagination);
		model.addAttribute("listConfigType", listConfigType);
		model.addAttribute("weixinMaterialId", weixinMaterialId);
		model.addAttribute("configType", configType);
		return "material/list_WeixinConfiguration";
	}
	/**
	 * 微信菜单list
	 */
	@RequestMapping("/material/v_listWeixinMenu.do")
	public String listWeixinMenu(Integer weixinMaterialId,String menuName, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		Pagination pagination = weixinMenuMng.getPage(weixinMaterialId, menuName,
				cpn(pageNo), CookieUtils.getPageSize(request));
		List<WeixinMenu> list = (List<WeixinMenu>) pagination.getList();
		for (WeixinMenu c : list) {
			if(c.getMenuType()!=null){
			c.setMenuTypeName(dicMng.findByDicCode("weixin_msg_type",
					c.getMenuType()).getDicName());
			}
		}
		List<Dictionary2> listMenuType = dicMng.getList("weixin_msg_type");
		model.addAttribute("pagination", pagination);
		model.addAttribute("weixinMaterialId", listMenuType);
		model.addAttribute("menuName", menuName);
		return "material/list_WeixinMenu";
	}
	@RequestMapping("/material/v_addWeixinMaterial.do")
	public String add(ModelMap model,HttpServletRequest request) {
		List<ShopInfo> shopList = shopMng.getAll(CmsUtils.getUser(request));
		List<Dictionary2> messageTypeList = dicMng.getList("message_type");
		model.addAttribute("shopList", shopList);
		model.addAttribute("messageTypeList", messageTypeList);
		return "material/add_WeixinMaterial";
	}
	/**
	 * 微信配置編輯
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/material/v_edit_weixinConfiguration.do")
	public String editWeixinConfiguration(Integer id,ModelMap model,HttpServletRequest request) {
		WeixinConfiguration weixinConfiguration =weixinConfigurationMng.findById(id);
		List<ShopInfo> shopList = shopMng.getAll(CmsUtils.getUser(request));
		List<Dictionary2> configTypeList = dicMng.getList("weixin_config_type");
		List<Dictionary2> specialServiceList = dicMng.getList("special_service");
		List<WeixinMaterial> weixinMaterialList = (List<WeixinMaterial>) manager.getPage(weixinConfiguration.getShop().getId(), null, 0, 0,CmsUtils.getUser(request)).getList();
		
		model.addAttribute("shopList", shopList);
		model.addAttribute("configTypeList", configTypeList);
		model.addAttribute("specialServiceList", specialServiceList);
		model.addAttribute("weixinConfiguration", weixinConfiguration);
		model.addAttribute("weixinMaterialList", weixinMaterialList);
		return "material/edit_WeixinConfiguration";
	}
	/**
	 * 微信菜单  編輯
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/material/v_edit_WeixinMenu.do")
	public String editWeixinMenu(Integer id,ModelMap model,HttpServletRequest request) {
		WeixinMenu weixinMenu =weixinMenuMng.findById(id);
		List<ShopInfo> shopList = shopMng.getAll(CmsUtils.getUser(request));
		List<Dictionary2> menuTypeList = dicMng.getList("weixin_msg_type");
		List<WeixinMaterial> weixinMaterialList = (List<WeixinMaterial>) manager.getPage(weixinMenu.getShop().getId(), null, 0, 0,CmsUtils.getUser(request)).getList();
		List<WeixinMenu> weixinMenuList = weixinMenuMng.getListWeixinMenuByLevel(Short.parseShort("1"));
		model.addAttribute("weixinMenu", weixinMenu);
		model.addAttribute("shopList", shopList);
		model.addAttribute("menuTypeList", menuTypeList);
		model.addAttribute("weixinMaterialList", weixinMaterialList);
		model.addAttribute("weixinMenuList", weixinMenuList);
		return "material/edit_WeixinMenu";
	}
	/**
	 * 微信配置新增
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/material/v_add_weixinConfiguration.do")
	public String addWeixinConfiguration(Integer id,ModelMap model,HttpServletRequest request) {
		WeixinConfiguration weixinConfiguration =new WeixinConfiguration();
			
		List<ShopInfo> shopList = shopMng.getAll(CmsUtils.getUser(request));
		List<Dictionary2> configTypeList = dicMng.getList("weixin_config_type");
		List<Dictionary2> specialServiceList = dicMng.getList("special_service");
		List<WeixinMaterial> weixinMaterialList = (List<WeixinMaterial>) manager.getPage(null, null, 0, 0,CmsUtils.getUser(request)).getList();
		
		model.addAttribute("shopList", shopList);
		model.addAttribute("configTypeList", configTypeList);
		model.addAttribute("specialServiceList", specialServiceList);
		model.addAttribute("weixinConfiguration", weixinConfiguration);
		model.addAttribute("weixinMaterialList", weixinMaterialList);
		return "material/add_WeixinConfiguration";
	}
	/**
	 *微信菜单 新增
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/material/v_add_WeixinMenu.do")
	public String addWeixinMenu(Integer id,ModelMap model,HttpServletRequest request) {
		WeixinMenu weixinMenu =new WeixinMenu();
		List<ShopInfo> shopList = shopMng.getAll(CmsUtils.getUser(request));
		List<Dictionary2> menuTypeList = dicMng.getList("weixin_msg_type");
		List<WeixinMaterial> weixinMaterialList = (List<WeixinMaterial>) manager.getPage(null, null, 0, 0,CmsUtils.getUser(request)).getList();
		List<WeixinMenu> weixinMenuList = weixinMenuMng.getListWeixinMenuByLevel(Short.parseShort("1"));
		model.addAttribute("shopList", shopList);
		model.addAttribute("weixinMenuList", weixinMenuList);
		model.addAttribute("menuTypeList", menuTypeList);
		model.addAttribute("weixinMaterialList", weixinMaterialList);
		model.addAttribute("weixinMenu", weixinMenu);
		return "material/add_WeixinMenu";
	}
	@RequestMapping("/material/v_to_edit_weixinMaterial.do")
	public String toEditWeixinMaterial(Integer materialId,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(materialId, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		model.addAttribute("materialId", materialId);
		return "material/to_edit_WeixinMaterial";
	}

	@RequestMapping("/material/v_edit_weixinMaterial.do")
	public String edit(Integer id, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		WeixinMaterial WeixinMaterial = manager.findById(id);
		List<ShopInfo> shopList = shopMng.getAll(CmsUtils.getUser(request));
		List<Dictionary2> messageTypeList = dicMng.getList("message_type");
		model.addAttribute("shopList", shopList);
		model.addAttribute("messageTypeList", messageTypeList);
		model.addAttribute("WeixinMaterial", WeixinMaterial);
		return "material/edit_weixinMaterial";
	}

	@RequestMapping("/material/	v_edit_weixinMaterialDetail.do")
	public String editWeixinMaterialDetail(Integer materialId,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(materialId, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		WeixinMaterialDetail weixinMaterialDetail;
		List<WeixinMaterialDetail> wmdList=weixinMaterialDetailMng.getListWeixinMaterialDetailByPId(materialId);
		if(wmdList==null||wmdList.size()==0){  //新增
			weixinMaterialDetail=new WeixinMaterialDetail();
		}else{
			weixinMaterialDetail=wmdList.get(0);
		}
		
		model.addAttribute("weixinMaterialDetail", weixinMaterialDetail);
		model.addAttribute("materialId", materialId);
		return "material/edit_weixinMaterialDetail";
	}

	@RequestMapping("/material/v_viewWeixinMaterial.do")
	public String view(Integer id, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		WeixinMaterial WeixinMaterial = manager.findById(id);
		model.addAttribute("WeixinMaterial", WeixinMaterial);
		return "material/view_WeixinMaterial";
	}

	@RequestMapping("/material/o_saveWeixinMaterial.do")
	public String save(WeixinMaterial bean, Integer shopId,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateSave(bean, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		bean = manager.save(bean, shopId);
		log.info("save WeixinMaterial id={}", bean.getId());
		cmsLogMng.operating(request, "WeixinMaterial.log.save", "id="
				+ bean.getId());
		return "redirect:v_listWeixinMaterial.do";
	}

	@RequestMapping("/material/o_update_weixinMaterial.do")
	public String update(WeixinMaterial bean, Integer shopId, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateUpdate(bean.getId(), request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		SimpleDateFormat simpleTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateTime = simpleTime.format(new Date());
		Timestamp t = Timestamp.valueOf(dateTime);

		bean.setUpdateTime(t);
		
		bean = manager.update(bean, shopId);
		model.addAttribute("message", "global.success");
		log.info("update WeixinMaterial success. id={}", bean.getId());
		cmsLogMng.operating(request, "WeixinMaterial.log.update", "id="
				+ bean.getId());
		return edit(bean.getId(), request, model);
	}
	@RequestMapping("/material/o_update_weixinMaterialDetail.do")
	public String updateWeixinMaterialDetail(WeixinMaterialDetail bean, Integer materialId, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateUpdate(materialId, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		if(bean.getId()==null){
			bean = weixinMaterialDetailMng.save(bean, materialId);
		}else{
		bean = weixinMaterialDetailMng.update(bean, materialId);
		}
		model.addAttribute("message", "global.success");
		log.info("update WeixinMaterialDetail success. id={}", bean.getId());
		cmsLogMng.operating(request, "WeixinMaterialDetail.log.update", "id="
				+ bean.getId());
		return editWeixinMaterialDetail(null, request, model);
	}
	@RequestMapping("/material/o_update_WeixinConfiguration.do")
	public String updateWeixinConfiguration(WeixinConfiguration bean, Integer shopId,Integer materialId, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateUpdate(materialId, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		ShopInfo shop = shopMng.findById(shopId);
		bean.setShop(shop);
		if(bean.getConfigType()==2){
			bean.setKeyword(null);
		}
		if(bean.getId()==null){
			SimpleDateFormat simpleTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String dateTime = simpleTime.format(new Date());
			Timestamp t = Timestamp.valueOf(dateTime);

			bean.setCreateTime(t);
			bean = weixinConfigurationMng.save(bean, materialId);
		}else{
			SimpleDateFormat simpleTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String dateTime = simpleTime.format(new Date());
			Timestamp t = Timestamp.valueOf(dateTime);

			bean.setUpdateTime(t);
		bean = weixinConfigurationMng.update(bean, materialId);
		}
		model.addAttribute("message", "global.success");
		log.info("update WeixinConfiguration success. id={}", bean.getId());
		cmsLogMng.operating(request, "WeixinConfiguration.log.update", "id="
				+ bean.getId());
		return listWeixinConfiguration(null, null,pageNo,request, model);
	}
	@RequestMapping("/material/o_update_WeixinMenu.do")
	public String updateWeixinMenu(WeixinMenu bean, Integer shopId,Integer materialId, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateUpdate(materialId, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		ShopInfo shop = shopMng.findById(shopId);
		bean.setShop(shop);
		if(bean.getId()==null){
			SimpleDateFormat simpleTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String dateTime = simpleTime.format(new Date());
			Timestamp t = Timestamp.valueOf(dateTime);

			bean.setCreateTime(t);
			bean = weixinMenuMng.save(bean, materialId);
		}else{
			SimpleDateFormat simpleTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String dateTime = simpleTime.format(new Date());
			Timestamp t = Timestamp.valueOf(dateTime);

			bean.setUpdateTime(t);
		bean = weixinMenuMng.update(bean, materialId);
		}
		model.addAttribute("message", "global.success");
		log.info("update WeixinMenu success. id={}", bean.getId());
		cmsLogMng.operating(request, "WeixinMenu.log.update", "id="
				+ bean.getId());
		return listWeixinMenu(null, null,pageNo,request, model);
	}
	@RequestMapping("/material/o_deleteWeixinMaterial.do")
	public String delete(Integer[] ids, Integer shopId, Short messageType,
			Integer pageNo, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateDelete(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		WeixinMaterial[] beans = manager.deleteByIds(ids);
		for (WeixinMaterial bean : beans) {
			log.info("delete WeixinMaterial id={}", bean.getId());
			cmsLogMng.operating(request, "WeixinMaterial.log.delete", "id="
					+ bean.getId() + ";name=" + bean.getShop().getName());
		}
		return list(shopId, messageType, pageNo, request, model);
	}

	private WebErrors validateSave(WeixinMaterial bean,
			HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		return errors;
	}

	private WebErrors validateEdit(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (vldExist(id, errors)) {
			return errors;
		}
		return errors;
	}

	private WebErrors validateUpdate(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (vldExist(id, errors)) {
			return errors;
		}
		// TODO 验证是否为管理员，管理员不允许修改。
		return errors;
	}

	private WebErrors validateDelete(Integer[] ids, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		errors.ifEmpty(ids, "ids");
		for (Integer id : ids) {
			vldExist(id, errors);
		}
		return errors;
	}

	private boolean vldExist(Integer id, WebErrors errors) {
		if (errors.ifNull(id, "id")) {
			return true;
		}
		WeixinMaterial entity = manager.findById(id);
		if (errors.ifNotExist(entity, Product.class, id)) {
			return true;
		}
		return false;
	}

	@Autowired
	private WeixinMaterialMng manager;
	@Autowired
	private WeixinMaterialDetailMng weixinMaterialDetailMng;
	@Autowired
	private WeixinConfigurationMng weixinConfigurationMng;
	@Autowired
	private WeixinMenuMng weixinMenuMng;
	
	@Autowired
	private CmsLogMng cmsLogMng;
	@Autowired
	private WiShopInfoMng shopMng;
	@Autowired
	private DictionaryMng dicMng;

}
